<!--
 * @Author: 清酒吖
 * @Date: 2022-01-20 11:02:38
 * @Email:  
 * @LastEditors:  
 * @LastEditTime: 2022-02-04 21:29:23
 * @Description: 
 * @version: x 1.0
-->

<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <i class="el-icon-search" />
        <span>筛选搜素</span>
        <el-button
          style="float: right"
          type="info"
          round
          @click="handleResetSearch()"
          >重置</el-button
        >
        <el-button
          style="float: right; margin-right: 15px"
          type="primary"
          round
          @click="search()"
          >查询</el-button
        >
        <el-button
          type="success"
          icon="el-icon-plus"
          @click="dialogFormVisible = true"
          >添加模板</el-button
        >
        <el-button type="danger" icon="el-icon-plus" @click="removebrath()"
          >批量删除</el-button
        >
      </div>
      <div class="text item">
        <el-form :inline="true" :model="findTemplate" class="demo-form-inline">
          <el-form-item label="输入搜索:">
            <el-input
              v-model="findTemplate.name"
              placeholder="模板名称"
              clearable
              @clear="search()"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <!-- <el-button type="primary" @click="onSubmit">查询</el-button> -->
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格数据  -->
    <el-table
      ref="multipleTable"
      :data="templateList"
      tooltip-effect="dark"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>

      <el-table-column prop="id" width="140" label="模板编号" align="center">
      </el-table-column>

      <el-table-column prop="name" label="模板名称" align="center">
      </el-table-column>

      <el-table-column prop="brands" label="模板关联品牌" align="center">
        <template slot-scope="scope">
          <div>
            <p>{{ scope.row.brands | jsonFormat }}</p>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="spec" label="模板关联规格" align="center">
        <template slot-scope="scope">
          <div>
            <p>{{ scope.row.spec | toString }}</p>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="" label="操作" align="center">
        <template slot-scope="scope">
          <div>
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="toUpdate(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="remove(scope.row)"
            ></el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="float: right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 添加模板 -->
    <el-dialog
      title="模板编辑"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form>
        <el-form-item label="模板名称" label-width="100px">
          <el-input v-model="entity.name"></el-input>
        </el-form-item>
        <el-form-item label="关联品牌" label-width="100px">
          <el-select v-model="entity.brands1" multiple placeholder="请选择品牌">
            <el-option
              v-for="item in brands"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联规格" label-width="100px">
          <el-select v-model="entity.spec1" multiple placeholder="请选择规格">
            <el-option
              v-for="item in specs"
              :key="item.id"
              :label="item.specName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="
            dialogFormVisible = false;
            entity = {};
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="saveTmp()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  findTemplate,
  addGoodsTemplate,
  updateGoodsTemplate,
  removeGoodsTemplate,
} from "@/api/template";
import { findSpec } from "@/api/goodsSpec";
import { findBrand } from "@/api/mallGoodsBrand";

export default {
  data() {
    return {
      pageNum: 1, // * 当前页数
      pageSize: 5, // * 当前页记录数
      total: 0, // * 总记录数
      pages: 0, // * 总页数
      multipleSelection: [], // * 表格多选数据
      templateList: [], // * 表格数据渲染
      findTemplate: {}, // * 查询条件
      brands: [], // * 品牌列表
      specs: [], // * 规格列表
      dialogFormVisible: false, // * 添加表单框显示状态
      entity: {
        name: "",
        brands1: [], // * 绑定下拉框
        brands: "", // * 传入后台的数据
        spec1: [], // * 绑定下拉框
        spec: "", // * 传入后台数据
      },
      ids: [],
    };
  },
  methods: {
    // * 选中的每行数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // * 每页显示记录数
    handleSizeChange(pageSizeNow) {
      // -> 监听当前页显示条数的变化
      console.log(pageSizeNow);
      this.pageSize = pageSizeNow;
      this.search();
    },
    // * 分页
    handleCurrentChange(pageNumNow) {
      //-> 监听当前页的变化
      console.log(pageNumNow);
      this.pageNum = pageNumNow;
      this.search();
    },
    // * 条件+分页查询
    search() {
      //-> 与服务器交互,调用查询API
      findTemplate(this.findTemplate, this.pageNum, this.pageSize).then(
        (res) => {
          // * 得到查询模板列表
          this.templateList = res.pageList;
          // * 查询的所有结果数
          this.total = res.total;
          // * 总页数
          this.pages = res.pages;
        }
      );
    },
    // * 重置查询
    handleResetSearch() {
      (this.findTemplate = {}), this.search();
    },
    // * 打开修改会话框
    toUpdate(row) {
      this.dialogFormVisible = true;

      this.entity.id = row.id;
      this.entity.name = row.name;

      //  品牌列表渲染
      var brandArr = JSON.parse(row.brands);
      var brandsIdArr = [];
      brandArr.forEach((item) => {
        brandsIdArr.push(item.id);
      });
      this.entity.brands1 = brandsIdArr;

      //  规格列表渲染
      var specArr = JSON.parse(row.spec);
      var specIdArr = [];
      specArr.forEach((item) => {
        specIdArr.push(item.id);
      });
      this.entity.spec1 = specIdArr;
    },
    // * 保存商品模板(增/改)
    saveTmp() {
      // 品牌处理
      var brandsArr = [];
      this.brands.forEach((item) => {
        if (this.entity.brands1.indexOf(item.id) != -1) {
          brandsArr.push({ id: item.id, name: item.name });
        }
      });
      this.entity.brands = JSON.stringify(brandsArr);
      // 规格处理
      var specArr = [];
      this.specs.forEach((item) => {
        if (this.entity.spec1.indexOf(item.id) != -1) {
          specArr.push({ id: item.id, name: item.specName });
        }
      });
      this.entity.spec = JSON.stringify(specArr);

      // 判断参数中是否存在id,如果存在是修改操作,不存在,则是添加操作
      if (this.entity.id) {
        // -> 与服务器交互,调用修改商品模板API
        updateGoodsTemplate(this.entity).then((res) => {
          this.$notify({
            title: res.success ? "成功" : "失败",
            message: res.msg,
            type: res.success ? "success" : "error",
          });
          this.pageNum = 1;
          this.search();
        });
      } else {
        // -> 与服务器交互,调用添加商品模板API
        addGoodsTemplate(this.entity).then((res) => {
          if (res.success) {
            this.$notify({
              title: "成功",
              message: res.msg,
              type: "success",
              duration: 3000,
            });
            this.pageNum = 1;
            this.search();
          } else {
            this.$notify.error({
              title: "失败",
              message: res.msg,
              type: "error",
              duration: 3000,
            });
          }
        });
      }

      // * 关闭弹出框
      this.dialogFormVisible = false;
      this.search();
    },
    // * 删除
    remove(row) {
      this.ids = [];
      this.ids.push(row.id);
      this.$confirm("此操作将永久删除该商品品牌, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // -> 与服务器交互,调用删除API
          removeGoodsTemplate(this.ids).then((res) => {
            this.$notify({
              title: res.success ? "成功" : "失败",
              message: res.msg,
              type: res.success ? "success" : "error",
              duration: 3000,
            });
            this.pageNum = 1;
            this.search();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // * 批量删除
    removebrath() {
      this.ids = [];
      this.multipleSelection.forEach((item) => {
        this.ids.push(item.id);
      });
      this.$confirm("此操作将永久删除该商品品牌, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // -> 与服务器交互,调用删除API
          removeGoodsTemplate(this.ids).then((res) => {
            this.$notify({
              title: res.success ? "成功" : "失败",
              message: res.msg,
              type: res.success ? "success" : "error",
              duration: 3000,
            });
            this.pageNum = 1;
            this.search();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  filters: {
    toString(source) {
      if (!source) {
        return "-";
      } else {
        var arr = [];
        var sourceArr = JSON.parse(source);
        sourceArr.forEach((item) => {
          arr.push(item.specName);
        });
        return arr.join(",");
      }
    },
  },
  created() {
    this.search();

    // # 获取所有品牌列表
    findBrand().then((res) => {
      this.brands = res.data;
    });

    // # 获取所有商品规格列表
    findSpec().then((res) => {
      this.specs = res.data;
    });
  },
};
</script>